const Queue = require('async/queue');
const _ = require('lodash');
const moment = require('moment');

module.exports = ({client, mysql, redis, status}) => {

  // 保存数据队列
  const queue = Queue((room, callback) => {
    try {

      (async () => {
        const today = moment().format('YYYY-MM-DD');

        const [[anchor, isNewAnchor], type] = await Promise.all([
          //创建或读取主播
          mysql.model.spider_anchor.findOrCreate(
            {
              where: {
                room: room.anchor.room + '', platform_id: room.platform.id,
              },
              defaults: {
                name: room.anchor.name,
                gender: room.anchor.gender,
                avatar: room.anchor.avatar,
                num_follower: room.data.num_follower,
              },
            }),
          //创建或读取直播分类
          new Promise(resolve => {
            if (room.type && room.type.id)
              return resolve(room.type);
            else if (_.isEmpty(room.type))
              return resolve({id: 1});
            mysql.model.spider_type.findOrCreate({
              where: {name: room.type},
            }).spread(type => {
              resolve(type);
            });
          }),

          //从redis读取直播时长，不会返回数据
          redis.getRedisLiveTime(room),
        ]);

        // 更新主播数据
        if (!isNewAnchor) {
          anchor.set({
            num_follower: room.data.num_follower,
            avatar: room.anchor.avatar,
            name: room.anchor.name,
            gender: room.anchor.gender,
          });
          anchor.save().then().catch(() => {});
        }

        const anchorDataKey = 'anchor_data:' + today,
          anchorDataField = room.platform.id + '_' + type.id + '_' + anchor.id;
        const redisAnchorData = await redis.hget(anchorDataKey,
          anchorDataField);
        const data = {}, isNewData = !redisAnchorData;
        if (isNewData) {
          data.platform_id = room.platform.id;
          data.type_id = type.id;
          data.anchor_id = anchor.id;

          data.num_watch = room.data.num_watch;
          data.num_follower = room.data.num_follower;
          data.num_live = room.data.num_live;
          data.num_gift = room.data.num_gift;
          data.is_new_anchor = isNewAnchor;
        } else {
          Object.assign(data, JSON.parse(redisAnchorData));

          //更新数据

          // 只记录最多的观看人次
          const num_watch = data.num_watch < room.data.num_watch ?
            room.data.num_watch :
            data.num_watch;

          // 累加从redis获取的直播时长
          const num_live = data.num_live + room.data.num_live;

          data.num_watch = num_watch;
          data.num_gift = room.data.num_gift;
          data.num_follower = room.data.num_follower;
          data.num_live = num_live;
        }

        await redis.hset(anchorDataKey, anchorDataField, JSON.stringify(data));
        status.save.finish++;

        callback();

      })();
    }
    catch (err) {
      status.save.error++;
      console.error('roomQueue', err);
      client.emitError(err);
      callback();
    }

  }, 1);

  queue.error = err => {
    status.save.error++;
    console.error('roomQueue', err);
    client.emitError(err);
  };

  //当前并发数，每5秒同步一次
  let currentConcurrency = 1;
  setInterval(async () => {
    const number = parseInt(await redis.get('config:room_queue'));
    if (isNaN(number) || currentConcurrency === number)
      return;
    console.log('改变roomQueue并发数量', number);
    currentConcurrency = number;
    queue.concurrency = number;
  }, 5000);

  return queue;
};